package com.example.hystrixDemo.service.observable.imp;

import com.netflix.hystrix.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * @author baohuajie
 * @description: TODO
 * @date 2020/9/1210:04 AM
 */
public class UserInfoServiceInfoCommand1 extends HystrixObservableCommand {

    private final Logger logger = LoggerFactory.getLogger(UserInfoServiceInfoCommand1.class);

    private UserInfoServiceImp userInfoServiceImp = new UserInfoServiceImp();

    public UserInfoServiceInfoCommand1() {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("queryUserInfoGroupKey"))
        .andCommandKey(HystrixCommandKey.Factory.asKey("queryUserInfoKey"))
        .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                .withExecutionTimeoutEnabled(true)
                .withExecutionTimeoutInMilliseconds(5000)
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD  )));
    }

    @Override
    protected Observable construct() {

        Observable<String> stringObservable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    try {
                        logger.info("=========UserInfoServiceCommand1当前端请求线程:{}=========", Thread.currentThread().getName());
                        subscriber.onNext(userInfoServiceImp.queryAddress());
                        subscriber.onNext(userInfoServiceImp.queryName());
                        subscriber.onCompleted();
                    } catch (Exception e) {
                        subscriber.onError(e);
                        e.printStackTrace();
                    }
                }
            }
        }).subscribeOn(Schedulers.io());

        return stringObservable;
    }

    /**
     * 处理失败回调函数
     * @return
     */
    @Override
    protected Observable resumeWithFallback() {

        Observable<Object> objectObservable = Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onNext("失败");
                    subscriber.onCompleted();
                }
            }
        }).subscribeOn(Schedulers.io());

        return objectObservable;
    }
}
